﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using BbsbWebService.Classes;
using BbsbWebService.Enums;

namespace BbsbWebService.Repositories
{
    public class ServerGroupRepository : GroupRepositoryBase
    {
        public override void Initialise()
        {
            if (File.Exists(AppSettings.SettingsFile.FullName))
            {
                XDocument doc = XDocument.Load(AppSettings.SettingsFile.FullName);

                var groups = doc.Descendants("AllGroups");
                foreach (var xmlGroup in groups.Elements("Group"))
                {
                    Group group = new Group
                    {
                        Id = new Guid(xmlGroup.Element("Id").Value),
                        Name = xmlGroup.Element("Name").Value,
                        Type = GetType(xmlGroup.Element("Type"))
                    };
                    Groups.Add(group);
                }
            }

        }

        public override void SaveGroup(Group group)
        {
            if (!string.IsNullOrEmpty(group.Name))
            {
                if (Groups.Any(o => o.Id == group.Id))
                {
                    for (int i = 0; i < Groups.Count; i++)
                    {
                        if (Groups[i].Id == group.Id)
                        {
                            Groups[i] = group;
                            break;
                        }
                    }
                }
                else
                {
                    Groups.Add(group);
                }
                AppSettings.Save();
            }
        }

        public override void RemoveGroup(Group group)
        {
            Groups.Remove(group);
            AppSettings.Save();
        }

        private static BbsbWebService.Enums.GroupType GetType(XElement xElement)
        {
            GroupType retVal = GroupType.Other;
            try
            {
                retVal = (GroupType)Enum.Parse(typeof(GroupType), xElement.Value);
            }
            catch (Exception) { }

            return retVal;
        }
    }
}
